package com.example.mechrevo.a3dtest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Message;
import com.threed.jpct.Camera;
import com.threed.jpct.CollisionEvent;
import com.threed.jpct.CollisionListener;
import com.threed.jpct.Config;
import com.threed.jpct.FrameBuffer;
import com.threed.jpct.Interact2D;
import com.threed.jpct.Light;
import com.threed.jpct.Loader;
import com.threed.jpct.Matrix;
import com.threed.jpct.Object3D;
import com.threed.jpct.SimpleVector;
import com.threed.jpct.Texture;
import com.threed.jpct.TextureInfo;
import com.threed.jpct.TextureManager;
import com.threed.jpct.World;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;


public class RenderView implements GLSurfaceView.Renderer{

    public World myWorld;
    private FrameBuffer frameBuffer;
    private Object3D selectedObj;
    Camera cam;
    public RenderView(Context context) {
        myWorld = new World();
        myWorld.setAmbientLight(25, 25, 25);
        Light light = new Light(myWorld);
        light.setIntensity(250,250,250);
        light.setPosition(new SimpleVector(0, 0, -15));

        cam = myWorld.getCamera();
        cam.setFOVLimits(0.1f,2.0f);
        cam.setFOV(1.08f);
        cam.setYFOV(1.92f);
        cam.setClippingPlanes(0f,2000f);

        System.out.println(cam.getFOV());
        System.out.println(cam.getYFOV());
        System.out.println(cam.getPosition());

        String[] names=Config.getParameterNames();
        for(String i:names){
            System.out.println(i);
        }
    }


    @Override
    public void onSurfaceChanged(GL10 gl, int w, int h) {
        if (frameBuffer != null) {
            frameBuffer.dispose();
        }
        frameBuffer = new FrameBuffer(gl, w, h);
    }


    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        gl.glClearColor(1.0f,1.0f,1.0f,0.3f);
    }


    @Override
    public void onDrawFrame(GL10 gl) {
        frameBuffer.clear(Color.TRANSPARENT);
        myWorld.renderScene(frameBuffer);
        myWorld.draw(frameBuffer);
        frameBuffer.display();
    }



    /**
     * 加载模型
     *
     * @param context
     */

    private String name="file_1";
    private int scale=130;
    public void addObject(Context context) {
        try {
//            createTextures(context,R.mipmap.texture1,"file1");
            Object3D[] objectsArray1 = Loader.loadOBJ(
                    context.getResources().getAssets().open(name+".obj"),
                    context.getResources().getAssets().open(name+".mtl"), 1f);
            selectedObj = Object3D.mergeAll(objectsArray1);
            selectedObj.setOrigin(new SimpleVector(0, 0, scale));
            selectedObj.rotateZ(3.1415926f);
            selectedObj.translate(0,0,0);
//            selectedObj.setTexture(new TextureInfo(TextureManager.getInstance().getTextureID("file1")));
            selectedObj.setName(name);
            selectedObj.strip();
            selectedObj.build();
            selectedObj.setRotationPivot(new SimpleVector(0,0,0));
//            addChildObj(context);
            /*将模型放入世界中*/
            myWorld.addObject(selectedObj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public void changeTexture(){
//        TextureManager.getInstance().getTextureID()
//        selectedObj.setTexture();
    }




    List<Object3D> childOBJ = new ArrayList<>();
    public void addChildObj(Context context){
        String name = "tractor";
        createTextures(context,R.mipmap.tractor,name);
        Object3D[] objectsArray1 ;
        try {
            objectsArray1 = Loader.loadOBJ(
                    context.getResources().getAssets().open(name+".obj"),
                    context.getResources().getAssets().open(name+".mtl"), 1f);
            Object3D childObj = Object3D.mergeAll(objectsArray1);
            childObj.setOrigin(new SimpleVector(0, 0, scale));
            childObj.rotateZ(0);
            childObj.translate(0,0,0);
            childObj.setTexture(name);
            childObj.setName(name);
            childObj.strip();
            childObj.build();
            childObj.setRotationPivot(new SimpleVector(0,0,0));
            selectedObj.addChild(childObj);
            childOBJ.add(childObj);
            myWorld.addObjects(childObj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @param p
     */
    public void removeChild(int p){
        if (childOBJ.size() > 0 && childOBJ.size() > p){
            Object3D o = childOBJ.get(p);
            selectedObj.removeChild( o);
            myWorld.removeObject( o);
            childOBJ.remove(p);
        }
    }




    /**
     * 移动
     *
     * @param incX
     * @param incY
     * @param incZ
     */
    public void applyTranslation(float incX, float incY, float incZ) {
        if (this.selectedObj != null) {
            SimpleVector objOrigin = this.selectedObj.getOrigin();
            SimpleVector currentPoition=this.selectedObj.getTransformedCenter();
            System.out.println(currentPoition);
            this.selectedObj.translate(incX, incY, incZ);
        }
    }




    /**
     * 旋转
     *
     * @param incX
     */
    public void applyRotationX(float incX) {
        if (this.selectedObj != null) {
            Matrix rm = selectedObj.getRotationMatrix();
            rm.rotateX(incX);
            selectedObj.setRotationMatrix(rm);
        }
    }


    /**
     * 旋转
     *
     * @param incY
     */
    public void applyRotationY(float incY) {
        if (this.selectedObj != null) {
            Matrix rm = selectedObj.getRotationMatrix();
            rm.rotateY(incY);
            this.selectedObj.setRotationMatrix(rm);
        }
    }




    public void touchObject(int x, int y) {
        SimpleVector dir = Interact2D.reproject2D3DWS(cam, frameBuffer, x, y).normalize();
        Object[] res= myWorld.calcMinDistanceAndObject3D(cam.getPosition(), dir, 100000000 /* a distance: picking will be ignoder if larger */);
        // cast the result
        Float    pickedDistance = (Float)    res[0];
        Object3D pickedObject   = (Object3D) res[1];
        // check if something has been picked immediately after
        if (pickedDistance != Object3D.COLLISION_NONE) {
            if (pickedObject.getID() == selectedObj.getID()) {
//                Toast.makeText(,"Object touched!",Toast.LENGTH_LONG).show();
            }
        }
    }



    /**
     * 相当于模型的皮肤
     *
     * @param context
     */
    private void createTextures(Context context,int id,String texTrueName) {
        Bitmap bitmap=BitmapFactory.decodeResource(context.getResources(),id);
        Texture texture = new Texture(bitmap);
        if(!TextureManager.getInstance().containsTexture(texTrueName)){
            TextureManager.getInstance().addTexture(texTrueName, texture);
        }
    }
}
